package com.shell.customer.invitation.service.impl;

import com.shell.bee.base.exception.UnCheckMsgException;
import com.shell.bee.base.utils.StringUtil;
import com.shell.bee.file.service.PubFileUploadService;
import com.shell.bee.file.vo.FileWapper;
import com.shell.bee.persistence.annotation.Pagination;
import com.shell.bee.persistence.model.PageLimit;
import com.shell.bee.persistence.service.impl.PersistentServiceImpl;
import com.shell.bee.report.excel.ExcelParser;
import com.shell.customer.base.dao.CusInvtDao;
import com.shell.customer.base.service.CusRecService;
import com.shell.customer.group.service.CusGrpService;
import com.shell.customer.invitation.InvtEvent;
import com.shell.customer.invitation.rx.InvtCusSubscriber;
import com.shell.customer.invitation.rx.SendInvtMsgSubscriber;
import com.shell.customer.invitation.rx.SetCusRelAndTagSubscriber;
import com.shell.customer.invitation.rx.UpdateInvtTimesSubscriber;
import com.shell.customer.invitation.service.InvtCusService;
import com.shell.customer.invitation.vo.Invitation;
import com.shell.customer.po.CusGrp;
import com.shell.customer.po.CusInvt;
import com.shell.customer.po.CusRec;
import com.shell.framework.utils.CommonDataUtil;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import rx.Observable;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service("invtCusService")
public class InvtCusServiceImpl extends PersistentServiceImpl<CusInvt> implements InvtCusService {
	@Autowired
	CusInvtDao cusInvtDao;
	@Autowired
	private CusRecService customerCService;
	@Resource(name = "${file.updownload.service}")
	private PubFileUploadService pubFileUploadService;
	@Autowired
	private InvtCusSubscriber invtCusSubscriber;
	@Autowired
	private SetCusRelAndTagSubscriber setCusRelAndTagSubscriber;
	@Autowired
	private SendInvtMsgSubscriber sendInvtMsgSubscriber;
	@Autowired
	private UpdateInvtTimesSubscriber updateInvtTimesSubscriber;
	@Autowired
	private CusGrpService cusGrpService;

	public void editInvitation(CusInvt invitation) {
		ivitationCus(invitation);
	}

	private void ivitationCus(CusInvt invitation) {
		CusRec customer = checkCusRegistered(invitation.getInviteeName());

		CusInvt oldCusInvt = checkCusInvtExist(invitation);
		if ((customer != null) && (oldCusInvt != null) && (customer.getCusName().equals(oldCusInvt.getInviteeName()))) {
			String msg = "";
			if (StringUtil.notEmpty(invitation.getInviterId())) {
				CusGrp cusGrp = (CusGrp) this.cusGrpService.selectByKey(invitation.getInviterId());
				if (cusGrp != null) {
					msg = "������ " + cusGrp.getGrpName() + " ������������" + invitation.getInviteeName();
				} else {
					msg = "������������" + invitation.getInviteeName() + "��������������";
				}
			} else {
				msg = "������������" + invitation.getInviteeName() + "��������������";
			}
			throw new UnCheckMsgException(msg);
		}
		InvtEvent invtEvent = new InvtEvent();
		invtEvent.setCusInvt(invitation);
		invtEvent.setCustomer(customer);
		invtEvent.setOldCusInvt(oldCusInvt);
		Observable<InvtEvent> observers = Observable.just(invtEvent);
		observers.subscribe(this.invtCusSubscriber);
		observers.subscribe(this.setCusRelAndTagSubscriber);
	}

	public String impt(String fileId, String inviteeCusType, String inviterId) throws Exception {
		String filePath = this.pubFileUploadService.getDownloadFile(fileId).getFile().getPath();
		List<CusInvt> cusInvts = ExcelParser.parseExcel(filePath, CusInvt.class);
		String msg = checkCusInvtImpt(cusInvts);
		if (StringUtil.notEmpty(msg)) {
			return msg;
		}
		for (CusInvt invt : cusInvts) {
			if (!StringUtil.emptyAndNull(inviteeCusType)) {
				invt.setInviteeCusType(inviteeCusType);
			} else {
				invt.setInviteeCusType(null);
			}
			invt.setInviterId(inviterId);
			ivitationCus(invt);
		}
		return "";
	}

	public void invite(String invtIds) {
		String[] invtIdArr = invtIds.split(",");
		List<Object> invtIdList = new ArrayList();
		Collections.addAll(invtIdList, invtIdArr);
		Example example = new Example(CusInvt.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andIn("invtId", invtIdList);
		List<CusInvt> cusInvts = selectByExample(example);

		InvtEvent invtEvent = new InvtEvent();
		invtEvent.setCusInvts(cusInvts);

		Observable<InvtEvent> observers = Observable.just(invtEvent);
		observers.subscribe(this.sendInvtMsgSubscriber);
		observers.subscribe(this.updateInvtTimesSubscriber);
	}

	@Pagination
	public List<Invitation> findInvitations(PageLimit limit, Invitation invitation) {
		if (StringUtil.notTrimEmpty(invitation.getInviteeName())) {
			invitation.setInviteeName(StringUtil.getParameterLike(invitation.getInviteeName()));
		}
		return this.cusInvtDao.findInvitations(invitation);
	}

	private CusInvt checkCusInvtExist(CusInvt cusInvt) {
		CusInvt invtTemp = new CusInvt();
		if (StringUtil.emptyAndNull(cusInvt.getInvtId())) {
			invtTemp.setInviterId(cusInvt.getInviterId());
			invtTemp.setInviteeName(cusInvt.getInviteeName());
			invtTemp.setInviteeCusType(cusInvt.getInviteeCusType());
		} else {
			invtTemp.setInvtId(cusInvt.getInvtId());
		}
		return (CusInvt) this.cusInvtDao.selectOne(invtTemp);
	}

	private CusRec checkCusRegistered(String cusName) {
		CusRec cus = new CusRec();
		cus.setCusName(cusName);
		return (CusRec) this.customerCService.selectOne(cus);
	}

	public List<CusInvt> getCusInvtByCusName(String inviteeName) {
		Example example = new Example(CusInvt.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("inviteeName", inviteeName);
		example.setOrderByClause("create_time asc");
		List<CusInvt> cusInvts = selectByExample(example);
		return cusInvts;
	}

	public int updateIvtCusNameByinviteeId(String cusName, String inviteeId) {
		return this.cusInvtDao.updateIvtCusNameByinviteeId(cusName, inviteeId);
	}

	public String checkCusInvtImpt(List<CusInvt> cusInvts) {
		int row = 0;
		StringBuffer msg = new StringBuffer();
		for (CusInvt invt : cusInvts) {
			row++;

			invt.setInviterId(CommonDataUtil.getCurEntId());
			if (StringUtil.emptyAndNull(invt.getInviteeName())) {
				msg.append("��").append(row).append("��������������������").append("$");
			}
			if (StringUtil.emptyAndNull(invt.getContactorName())) {
				msg.append("��").append(row).append("������������������").append("$");
			}
			if (StringUtil.emptyAndNull(invt.getContactorPhone())) {
				msg.append("��").append(row).append("������������������������").append("$");
			} else if (!isChinaPhoneLegal(invt.getContactorPhone())) {
				msg.append("��").append(row).append("����������������������").append("$");
			}
		}
		return msg.toString();
	}

	private boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
		String regExp = "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
		Pattern p = Pattern.compile(regExp);
		Matcher m = p.matcher(str);
		return m.matches();
	}

	@Pagination
	public List<Invitation> findInvitationsForGroup(PageLimit limit, Invitation invitation) {
		if (StringUtil.notTrimEmpty(invitation.getInviteeName())) {
			invitation.setInviteeName(StringUtil.getParameterLike(invitation.getInviteeName()));
		}
		return this.cusInvtDao.findInvitationsForGroup(invitation);
	}

	public List<Invitation> countInviteNum(String cusId) {
		return this.cusInvtDao.countInviteNum(cusId);
	}
}